package com.campus.merchant.config;

import com.campus.merchant.handler.NativeWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置类
 * 同时支持STOMP协议和原生WebSocket
 */
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketConfigurer, WebSocketMessageBrokerConfigurer {

    @Autowired
    private NativeWebSocketHandler nativeWebSocketHandler;

    /**
     * 注册原生WebSocket处理器
     * @param registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册原生WebSocket处理器，支持uni-app小程序
        registry.addHandler(nativeWebSocketHandler, "/ws")
                .setAllowedOriginPatterns("*");
    }

    /**
     * 注册STOMP协议的节点(endpoint),并映射指定的url
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个STOMP的endpoint,并指定使用SockJS协议,允许跨域
        registry.addEndpoint("/ws-stomp").setAllowedOriginPatterns("*").withSockJS();
        
        // 为传统Web客户端添加STOMP支持，不使用SockJS
        registry.addEndpoint("/ws-stomp").setAllowedOriginPatterns("*");
    }

    /**
     * 配置消息代理(Message Broker)
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 广播式应配置一个/topic消息代理, 群发（@SendTo）
        // 点对点式（@SendToUser）应配置一个/user消息代理
        registry.enableSimpleBroker("/topic", "/user");
        // 全局使用的消息前缀（客户端订阅路径上会体现出来）
        registry.setApplicationDestinationPrefixes("/app");
        // 点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
        registry.setUserDestinationPrefix("/user/");
    }
}